//
//  PreferencesViewController.m
//  TwitterFon
//
//  Created by koolearn on 11-4-9.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PreferencesViewController.h"
#import "User.h"
#import "TwitterClient.h"
#import "GuaziAppDelegate.h"
#import "GroupListEditViewController.h"
#import "MyCardsViewController.h"


@implementation PreferencesViewController


@synthesize textFieldBeingEdited;
@synthesize userName;
@synthesize password;


- (void) save : (id) sender 
{
	if ( textFieldBeingEdited != nil ) {
		if ( textFieldBeingEdited.tag == kTagUserName ) {
			self.userName = textFieldBeingEdited.text;
		}
		else if ( textFieldBeingEdited.tag == kTagPassword ) {
			self.password = textFieldBeingEdited.text;
		}
		
		[textFieldBeingEdited resignFirstResponder];
	}
	
	NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
    
    User* olduser = [GuaziAppDelegate getAppDelegate].user;
    if ( [olduser.name compare:userName]!=NSOrderedSame || [olduser.password compare:password]!=NSOrderedSame) {
        User* user = [TwitterClient verifyAccount:userName password:password];
        if ( user == nil ) {
            [GuaziAppDelegate showAlert:@"帐户认证失败，请输入正确的用户名和密码"];
            return;
        }

        user.name = userName;
        user.password = password;
        [[GuaziAppDelegate getAppDelegate] switchUser:user];
    }
    
	[userDefault setObject:[NSNumber numberWithBool:clearLocalCache] forKey:kKeyClearLocalCache];
	[userDefault setObject:[NSNumber numberWithBool:loadAllTabOnLaunch] forKey:kKeyLoadAllTabOnLaunch];
	[userDefault setObject:[NSNumber numberWithBool:autoRefresh] forKey:kKeyAutoRefresh];
	[userDefault setObject:[NSNumber numberWithBool:autoScrollToFirstUnread] forKey:kKeyAutoScrollToFirstUnread];
	[userDefault synchronize];
	
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                        message:@"已经成功保存了您的设置" 
                                                       delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
    [alertView release];

}


- (void) switchChanged : (id) sender
{
	UISwitch* switchCtrl = (UISwitch*) sender;
	if ( switchCtrl.tag == kTagClearLocalCache ) {
		clearLocalCache = switchCtrl.on;
	}
	else if ( switchCtrl.tag == kTagLoadAllTabOnLaunch ) {
		loadAllTabOnLaunch = switchCtrl.on;
	}
	else if ( switchCtrl.tag == kTagAutoRefresh ) {
		autoRefresh = switchCtrl.on;
	}
	else if ( switchCtrl.tag == kTagAutoScrollToFirstUnread ) {
		autoScrollToFirstUnread = switchCtrl.on;
	}
}



#pragma mark -
#pragma mark View lifecycle


- (void) loadView
{
	self.view = [[[NSBundle mainBundle] loadNibNamed:@"PreferencesView" owner:self options:nil] lastObject];
	
	UIBarButtonItem* rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" 
																	style:UIBarButtonItemStyleDone 
																   target:self action:@selector(save:)];
	self.navigationItem.rightBarButtonItem = rightButton;
	[rightButton release];
	
	NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
	
	//self.userName = [userDefault stringForKey:kKeyUserName];
    self.userName = [GuaziAppDelegate getAppDelegate].user.name;
	if ( userName == nil ) self.userName = @"";
	
	//self.password = [userDefault stringForKey:kKeyPassword];
    self.password = [GuaziAppDelegate getAppDelegate].user.password;
	if ( password == nil ) self.password = @"";
	
	if ( [userDefault objectForKey:kKeyClearLocalCache] != nil ) {
		clearLocalCache = [userDefault boolForKey:kKeyClearLocalCache];
	}
	else {
		clearLocalCache = NO;
	}
	
	if ( [userDefault objectForKey:kKeyLoadAllTabOnLaunch] != nil ) {
		loadAllTabOnLaunch = [userDefault boolForKey:kKeyLoadAllTabOnLaunch];
	}   
	else {
		loadAllTabOnLaunch = YES;
	}
	
	if ( [userDefault objectForKey:kKeyAutoRefresh] != nil ) {
		autoRefresh = [userDefault boolForKey:kKeyAutoRefresh];
	}
	else {
		autoRefresh = YES;
	}
	
	if ( [userDefault objectForKey:kKeyAutoScrollToFirstUnread] != nil ) {
		autoScrollToFirstUnread = [userDefault boolForKey:kKeyAutoScrollToFirstUnread];
	}
	else {
		autoScrollToFirstUnread = YES;
	}
}



/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ( section == kSettingAccountSection ) {
		return 2;
	}
	else if (section == kSettingOtherSection ) {
		return 4;
	}
	else if (section == kSettingGroup ) {
		return 1;
	}
    else if ( section == kSettingCard ) {
        return 1;
    }
	else {
		return 0;
	}
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"PreferenceCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	
	int y = ( cell.frame.size.height - 20 ) / 2;
	if ( section == kSettingAccountSection ) {
		CGRect rect = CGRectMake(0, y, 90, 20);
		UILabel* label = [[UILabel alloc] initWithFrame:rect];
		label.font = [UIFont systemFontOfSize:16];
		label.textAlignment = UITextAlignmentRight;
		label.userInteractionEnabled = NO;
		[cell.contentView addSubview:label];
		
		rect = CGRectMake( 100, y, 180, 20);
		UITextField* textField = [[UITextField alloc] initWithFrame:rect];
		textField.returnKeyType = UIReturnKeyDone;
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		textField.autocorrectionType = UITextAutocorrectionTypeNo;
		textField.delegate = self;
		[textField addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
		[cell.contentView addSubview:textField];

		if ( row == 0 ) {
			label.text = @"用户名";
			textField.tag = kTagUserName;
			textField.text = userName;
			textField.placeholder = @"请输入用户名";
		}
		else {
			label.text = @"密码";
			textField.tag = kTagPassword;
			textField.text = password;
			textField.secureTextEntry = YES;
			textField.placeholder = @"请输入密码";
		}

		[label release];
		[textField release];
	}
	else if (section == kSettingOtherSection) {
		CGRect rect = CGRectMake(0, y, 120, 20);
		UILabel* label = [[UILabel alloc] initWithFrame:rect];
		label.font = [UIFont systemFontOfSize:16];
		label.textAlignment = UITextAlignmentRight;
		label.userInteractionEnabled = NO;
		[cell.contentView addSubview:label];
		
		rect = CGRectMake( 180, y-4, 120, 20 );
		UISwitch* switchCtrl = [[UISwitch alloc] initWithFrame:rect];
		[switchCtrl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
		[cell.contentView addSubview:switchCtrl];
		
		if ( row == 0 ) {
			label.text = @"清除本地缓存";
			switchCtrl.tag = kTagClearLocalCache;
			switchCtrl.on = clearLocalCache;
		}
		else if ( row == 1 ) {
			label.text = @"启动时读入数据";
			switchCtrl.tag = kTagLoadAllTabOnLaunch;
			switchCtrl.on = loadAllTabOnLaunch;
		}
		else if ( row == 2 ) {
			label.text = @"自动刷新";
			switchCtrl.tag = kTagAutoRefresh;
			switchCtrl.on = autoRefresh;
		}
		else if ( row == 3 ) {
			label.text = @"自动滚屏";
			switchCtrl.tag = kTagAutoScrollToFirstUnread;
			switchCtrl.on = autoScrollToFirstUnread;
		}
		
		[label release];
		[switchCtrl release];
	}
	else if ( section == kSettingGroup ) {
		cell.textLabel.textAlignment = UITextAlignmentRight;
		cell.textLabel.font = [UIFont systemFontOfSize:18];
		cell.textLabel.text = @"设置分组";
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
    else if ( section == kSettingCard ) {
        cell.textLabel.textAlignment = UITextAlignmentRight;
        cell.textLabel.font = [UIFont systemFontOfSize:18];
        cell.textLabel.text = @"名片管理";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (NSIndexPath*) tableView : (UITableView*) tableView willSelectRowAtIndexPath : (NSIndexPath*) indexPath {
	if ( indexPath.section == kSettingGroup || indexPath.section == kSettingCard ) return indexPath;
	return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if ( indexPath.section == kSettingGroup ) {
		GroupListEditViewController* controller = [[GroupListEditViewController alloc] initWithStyle:UITableViewStylePlain];
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];
	}
    else if ( indexPath.section == kSettingCard ) {
        MyCardsViewController* controller = [[MyCardsViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }
}


#pragma mark -
#pragma mark textField Delete

- (IBAction) textFieldDone : (id) sender {
	[sender resignFirstResponder];
}


- (void) textFieldDidBeginEditing:(UITextField *)textField
{
	self.textFieldBeingEdited = textField;
}


- (void) textFieldDidEndEditing:(UITextField *)textField
{
	if ( textField.tag == kTagUserName ) {
		self.userName = textField.text;
	}
	else if ( textField.tag == kTagPassword ) {
		self.password = textField.text;
	}
	self.textFieldBeingEdited = nil;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	self.textFieldBeingEdited = nil;
	self.userName = nil;
	self.password = nil;
	[super viewDidLoad];
}


- (void)dealloc {
	[textFieldBeingEdited release];
	[userName release];
	[password release];
    [super dealloc];
}


@end

